package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.base.BaseFragment;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.sdsmdg.tastytoast.TastyToast;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ReleaseDynamicFragment extends BaseFragment implements View.OnClickListener, TextWatcher {

    private ImageView backIv;
    private TextView titleTv, rightTv;
    private EditText titleEt, addressEt, contantEt;
    private TextView contantNumTv, picNumTv;
    private ImageView dynamicPic;

    private ArrayList<AlbumFile> mAlbumFiles;


    public static ReleaseDynamicFragment newInstance() {
        ReleaseDynamicFragment releaseDynamicFragment = new ReleaseDynamicFragment();
        Bundle bundle = new Bundle();
        releaseDynamicFragment.setArguments(bundle);
        return releaseDynamicFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int setView() {
        return R.layout.fragment_release_dynamic;
    }

    @Override
    protected void init(View view) {
        backIv = view.findViewById(R.id.layout_head_back_iv);
        titleTv = view.findViewById(R.id.layout_head_title_tv);
        rightTv = view.findViewById(R.id.layout_head_right_tv);
        titleEt = view.findViewById(R.id.release_dynamic_title_et);
        addressEt = view.findViewById(R.id.release_dynamic_address_et);
        contantEt = view.findViewById(R.id.release_dynamic_contant_et);
        contantNumTv = view.findViewById(R.id.contant_lengh_tv);
        picNumTv = view.findViewById(R.id.pic_num_tv);
        dynamicPic = view.findViewById(R.id.release_dynamic_pic);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        titleTv.setText("发布动态");
        rightTv.setText("发布");
        setListener();
    }

    private void setListener() {
        backIv.setOnClickListener(this);
        rightTv.setOnClickListener(this);
        contantEt.addTextChangedListener(this);
        dynamicPic.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_head_back_iv:
                getActivity().getSupportFragmentManager().popBackStack();
                break;
            case R.id.layout_head_right_tv:
//                httpReleaseDynamic();
                break;
            case R.id.release_dynamic_pic:
                selectAlbum();
                break;
        }
    }

    /**
     * Select picture, from album.
     */
    private void selectAlbum() {
        Album.album(this)
                .multipleChoice()
                .columnCount(2)
                .selectCount(9)
                .camera(true)
                .cameraVideoQuality(1)
                .cameraVideoLimitDuration(Integer.MAX_VALUE)
                .cameraVideoLimitBytes(Integer.MAX_VALUE)
                .checkedList(mAlbumFiles)
                .widget(
                        Widget.newDarkBuilder(getActivity())
                                .title("图片选择")
                                .build()
                )
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {
                        mAlbumFiles = result;
                        List<String> list = new ArrayList<>();
                        List<String> nameList = new ArrayList<>();
                        List<Integer> intList = new ArrayList<>();
                        for (int i = 0; i < result.size(); i++) {
                            if (result.get(i).getMediaType() == AlbumFile.TYPE_IMAGE) {
                                list.add(result.get(i).getPath());
                                nameList.add(result.get(i).getBucketName());
                            } else {
                                intList.add(i);
                            }
                        }
                        upImg(list,nameList,intList);

                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        TastyToast.makeText(getActivity(), "已取消", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                    }
                })
                .start();
    }

    /**
     * 上传图片
     */
    private void upImg(List<String> mImageList, List<String> nameList,List<Integer> intList) {

        if (intList.size() > 0){
            TastyToast.makeText(getActivity(), "暂不支持视频上传", TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
        }
        HttpUtils.doMoreFile(HttpContant.URL + HttpContant.UpImgUri + "2"
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , mImageList
                , nameList
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i("qqqqqq",e+"");

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.i("qqqqqq",response.body().string());

                    }
                });

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event) {
        switch (event.getCls()) {
            case "requestFail":
                TastyToast.makeText(getActivity(), "请求失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                break;
            case "releaseDynamic":
                Log.i("releaseDynamic",event.getData().toString());
                break;
            case "upMoreImg":
                Log.i("upMoreImg", event.getData().toString());
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 发布动态
     */
    private void httpReleaseDynamic(String essaytitle, int placeid, String placename, String placecity, String essay, List essaypicture, String hidemember) {
        Map<String, Object> map = new HashMap<>();
        map.put("essaytitle", essaytitle);
        map.put("placeid", placeid);
        map.put("placename", placename);
        map.put("placecity", placecity);
        map.put("essay", essay);
        map.put("essaypicture", essaypicture);
        map.put("hidemember", hidemember);

        HttpUtils.PutCookie(HttpContant.URL + HttpContant.ReleaseDynamic
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , map
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("releaseDynamic", response.body().string()));
                    }
                });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (TextUtils.isEmpty(contantEt.getText())) {
            int num1 = contantEt.getText().length();
            contantNumTv.setText(num1 + "/100");
        }
    }


}
